<template>
  <div class="home-page">
    <!-- 轮播图区域 -->
    <div class="banner-section">
      <el-carousel height="200px" indicator-position="outside">
        <el-carousel-item v-for="item in banners" :key="item.id">
          <div :style="{ backgroundColor: item.color }" class="banner-item">
            <h3>{{ item.title }}</h3>
            <p>{{ item.subtitle }}</p>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <div class="section-title">商品分类</div>
      <div class="category-grid">
        <div
            v-for="category in topCategories"
            :key="category.id"
            class="category-item"
            @click="goToCategory(category.id)"
        >
          <div class="category-icon">
            <img
                v-if="category.icon"
                :alt="category.name"
                :src="category.icon"
                class="category-icon-img"
                @error="handleImageError"
            />
            <el-icon v-else :size="24" class="default-icon">
              <Box/>
            </el-icon>
          </div>
          <span class="category-name">{{ category.name }}</span>
        </div>
      </div>
    </div>

    <!-- 热门商品 -->
    <div class="hot-products">
      <div class="section-title">
        <span>热门商品</span>
        <el-button type="text" @click="viewMoreProducts">查看更多</el-button>
      </div>
      <div class="product-grid">
        <div
            v-for="product in hotProducts"
            :key="product.id"
            class="product-card"
            @click="goToProductDetail(product.id)"
        >
          <div class="product-image">
            <el-image
                :alt="product.name"
                :src="product.mainImage || '/placeholder.jpg'"
                fit="cover"
            />
          </div>
          <div class="product-info">
            <h4 class="product-name">{{ product.name }}</h4>
            <p class="product-subtitle">{{ product.subtitle }}</p>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">
                ¥{{ product.originalPrice }}
              </span>
            </div>
            <div class="product-stats">
              <span class="sales">已售{{ product.sales }}件</span>
            </div>
          </div>
          <div class="product-actions">
            <el-button
                :loading="addingToCart[product.id]"
                size="small"
                type="primary"
                @click.stop="addToCart(product)"
            >
              加入购物车
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 推荐商品 -->
    <div class="recommend-products">
      <div class="section-title">
        <span>为您推荐</span>
      </div>
      <div class="product-grid">
        <div
            v-for="product in recommendProducts"
            :key="product.id"
            class="product-card"
            @click="goToProductDetail(product.id)"
        >
          <div class="product-image">
            <el-image
                :alt="product.name"
                :src="product.mainImage || '/placeholder.jpg'"
                fit="cover"
            />
          </div>
          <div class="product-info">
            <h4 class="product-name">{{ product.name }}</h4>
            <p class="product-subtitle">{{ product.subtitle }}</p>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">
                ¥{{ product.originalPrice }}
              </span>
            </div>
            <div class="product-stats">
              <span class="sales">已售{{ product.sales }}件</span>
            </div>
          </div>
          <div class="product-actions">
            <el-button
                :loading="addingToCart[product.id]"
                size="small"
                type="primary"
                @click.stop="addToCart(product)"
            >
              加入购物车
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button :loading="loading" @click="loadMoreProducts">
        加载更多商品
      </el-button>
    </div>

    <!-- 没有更多数据提示 -->
    <div v-else-if="recommendProducts.length > 0" class="no-more">
      <span>没有更多商品了</span>
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {Box} from '@element-plus/icons-vue'
import {getHotProducts, getNewProducts} from '@/api/product'
import {getFirstLevelCategories} from '@/api/category'
import {addToCart as addToCartApi} from '@/api/cart'
import {useCartStore, useUserStore} from '@/store'

// 路由相关
const router = useRouter()
const route = useRoute()

// 状态管理
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = 10

// 轮播图数据
const banners = ref([
  {
    id: 1,
    title: '欢迎来到Easy Mart',
    subtitle: '优质商品，优惠价格',
    color: '#409eff'
  },
  {
    id: 2,
    title: '新品上市',
    subtitle: '最新商品等你来抢购',
    color: '#67c23a'
  },
  {
    id: 3,
    title: '限时优惠',
    subtitle: '精选商品特价销售',
    color: '#e6a23c'
  }
])

// 商品数据
const topCategories = ref([])
const hotProducts = ref([])
const recommendProducts = ref([])

// 加入购物车状态
const addingToCart = reactive({})

// 获取顶级分类
const fetchTopCategories = async () => {
  try {
    const response = await getFirstLevelCategories()
    topCategories.value = response.data.slice(0, 8) // 只显示前8个分类
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取热门商品
const fetchHotProducts = async () => {
  try {
    const response = await getHotProducts({limit: 8})
    hotProducts.value = response.data || []
  } catch (error) {
    console.error('获取热门商品失败:', error)
  }
}

// 获取推荐商品
const fetchRecommendProducts = async (page = 1) => {
  try {
    loading.value = true
    const response = await getNewProducts({
      limit: pageSize
    })

    if (page === 1) {
      recommendProducts.value = response.data || []
    } else {
      recommendProducts.value.push(...(response.data || []))
    }

    hasMore.value = false // 推荐商品不支持分页
  } catch (error) {
    console.error('获取推荐商品失败:', error)
    ElMessage.error('获取商品失败')
  } finally {
    loading.value = false
  }
}

// 加载更多商品
const loadMoreProducts = () => {
  currentPage.value++
  fetchRecommendProducts(currentPage.value)
}

// 加入购物车
const addToCart = async (product) => {
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    addingToCart[product.id] = true

    await addToCartApi({
      productId: product.id,
      quantity: 1
    })

    ElMessage.success('已加入购物车')
    // 更新购物车统计
    await cartStore.fetchCartSummary()
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  } finally {
    addingToCart[product.id] = false
  }
}

// 导航方法
const goToCategory = (categoryId) => {
  router.push({path: '/category', query: {categoryId}})
}

const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

const viewMoreProducts = () => {
  router.push('/category')
}

// 处理图片加载错误
const handleImageError = (event) => {
  // 图片加载失败时隐藏图片，显示默认图标
  event.target.style.display = 'none'
  const parentElement = event.target.parentElement
  const defaultIcon = parentElement.querySelector('.default-icon')
  if (defaultIcon) {
    defaultIcon.style.display = 'block'
  }
}

// 监听路由查询参数变化（搜索功能）
watch(
    () => route.query.keyword,
    (keyword) => {
      if (keyword) {
        // 如果有搜索关键词，可以在这里处理搜索逻辑
        console.log('搜索关键词:', keyword)
        // 这里可以调用搜索API或跳转到搜索结果页面
      }
    },
    {immediate: true}
)

// 组件挂载时获取数据
onMounted(() => {
  fetchTopCategories()
  fetchHotProducts()
  fetchRecommendProducts()
})
</script>

<style scoped>
.home-page {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 轮播图区域 */
.banner-section {
  margin-bottom: 2rem;
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
}

.banner-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: white;
  text-align: center;
  background: var(--gradient-primary);
  position: relative;
}

.banner-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  z-index: 1;
}

.banner-item h3,
.banner-item p {
  position: relative;
  z-index: 2;
}

.banner-item h3 {
  font-size: 1.75rem;
  font-weight: 700;
  margin: 0 0 0.75rem 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.banner-item p {
  font-size: 1rem;
  margin: 0;
  opacity: 0.95;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

/* 通用区块样式 */
.category-nav,
.hot-products,
.recommend-products {
  background: var(--bg-card);
  margin-bottom: 2rem;
  padding: 2rem;
  border-radius: var(--radius-2xl);
  box-shadow: var(--shadow-md);
  transition: all 0.3s ease;
  border: 1px solid var(--border-light);
}

.category-nav:hover,
.hot-products:hover,
.recommend-products:hover {
  box-shadow: var(--shadow-xl);
  transform: translateY(-2px);
  border-color: var(--primary-200);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  font-size: 1.25rem;
  font-weight: 700;
  color: var(--text-primary);
  position: relative;
  padding-bottom: 0.75rem;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 4rem;
  height: 3px;
  background: var(--gradient-primary);
  border-radius: var(--radius-sm);
}

/* 分类导航 */
.category-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1.5rem 1rem;
  border-radius: var(--radius-xl);
  cursor: pointer;
  transition: all 0.3s ease;
  background: var(--bg-secondary);
  border: 1px solid var(--border-light);
}

.category-item:hover {
  background: var(--primary-50);
  transform: translateY(-4px);
  border-color: var(--primary-color);
  box-shadow: var(--shadow-lg);
}

.category-icon {
  width: 3rem;
  height: 3rem;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--gradient-light);
  color: white;
  border-radius: var(--radius-xl);
  margin-bottom: 0.75rem;
  position: relative;
}

.category-icon-img {
  width: 2rem;
  height: 2rem;
  object-fit: cover;
  border-radius: var(--radius-md);
}

.default-icon {
  display: none;
}

.category-name {
  font-size: 14px;
  color: #606266;
  text-align: center;
}

/* 商品网格 */
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.product-card {
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-md);
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  border: 1px solid var(--border-light);
}

.product-card:hover {
  transform: translateY(-6px);
  box-shadow: var(--shadow-xl);
  border-color: var(--primary-color);
}

.product-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: var(--gradient-primary);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover::before {
  opacity: 1;
}

.product-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.product-subtitle {
  font-size: 12px;
  color: #909399;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.3;
}

.product-price {
  margin-bottom: 12px;
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.current-price {
  font-size: 1.125rem;
  font-weight: 700;
  color: var(--primary-color);
}

.original-price {
  font-size: 0.875rem;
  color: var(--text-tertiary);
  text-decoration: line-through;
}

.product-stats {
  font-size: 12px;
  color: #909399;
}

.product-actions {
  padding: 0 12px 12px;
}

.product-actions .el-button {
  width: 100%;
}

/* 加载更多和无更多数据 */
.load-more,
.no-more {
  text-align: center;
  padding: 20px;
}

.no-more span {
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
/* 平板端 */
@media (max-width: 1024px) {
  .category-grid {
    grid-template-columns: repeat(6, 1fr);
    gap: 15px;
  }

  .product-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
  }
}

/* 移动端 */
@media (max-width: 768px) {
  .home-page {
    padding: 0;
  }

  .home-container {
    padding: 1rem;
  }

  .banner-section {
    margin-bottom: 1.5rem;
  }

  .banner-item {
    height: 160px;
  }

  .banner-item h3 {
    font-size: 1.5rem;
  }

  .banner-item p {
    font-size: 0.875rem;
  }

  .category-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
  }

  .category-item {
    padding: 1rem 0.5rem;
  }

  .category-icon {
    width: 2.5rem;
    height: 2.5rem;
    margin-bottom: 0.5rem;
  }

  .category-icon-img {
    width: 1.5rem;
    height: 1.5rem;
  }

  .category-name {
    font-size: 0.75rem;
    line-height: 1.2;
  }

  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
  }

  .product-image {
    height: 140px;
  }

  .product-info {
    padding: 1rem;
  }

  .product-name {
    font-size: 0.875rem;
    line-height: 1.3;
    margin-bottom: 0.5rem;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .product-price {
    margin-bottom: 0.75rem;
  }

  .current-price {
    font-size: 1rem;
  }

  .original-price {
    font-size: 0.75rem;
  }

  .add-to-cart-btn {
    font-size: 0.75rem;
    padding: 0.5rem 1rem;
    width: 100%;
  }

  .category-nav,
  .hot-products,
  .recommend-products {
    padding: 1.5rem;
    margin-bottom: 1.5rem;
  }

  .section-title {
    font-size: 1.125rem;
    margin-bottom: 1rem;
  }
}

/* 小屏手机 */
@media (max-width: 480px) {
  .banner-section .el-carousel {
    height: 150px;
  }

  .banner-item h3 {
    font-size: 18px;
  }

  .banner-item p {
    font-size: 12px;
  }

  .category-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
  }

  .category-item {
    padding: 6px;
  }

  .category-icon {
    width: 32px;
    height: 32px;
  }

  .category-icon-img {
    width: 20px;
    height: 20px;
  }

  .category-name {
    font-size: 11px;
  }

  .product-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .product-card {
    padding: 8px;
  }

  .product-image {
    height: 100px;
  }

  .product-name {
    font-size: 12px;
  }

  .product-price {
    font-size: 13px;
  }

  .section-title {
    font-size: 15px;
  }

  .category-nav,
  .hot-products,
  .recommend-products {
    padding: 10px;
    margin-bottom: 8px;
  }
}
</style>